package com.tanhua.sso.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Value("${jwt.secret}")
    private String secret;

    @Override
    public String loginVerification(String phone, String code) {
        boolean isNew = false;

        String redisKey = "CHECK_CODE_" + phone;
        if (!StringUtils.equals(this.redisTemplate.opsForValue().get(redisKey), code)) {
            return null;//用户输入验证码跟redis查询的不一致
        }

        //验证码在校验完成后，需要废弃
        this.redisTemplate.delete(redisKey);

        //去数据库中查找该手机是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", phone);
        User user = userMapper.selectOne(wrapper);

        //不存在则为新用户
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword("123456");

            this.userMapper.insert(user);
            isNew = true;
        }

        //生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", user.getId());

        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12小时后过期
                .compact();

        try {
            //发送用户登录成功的消息
            Map<String, Object> msg = new HashMap<>();
            msg.put("id", user.getId());
            msg.put("date", System.currentTimeMillis());

            this.rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (MessagingException e) {
            log.error("发送消息失败！", e);
        }

        return token + "|" + isNew;
    }

    @Override
    public User queryUserByToken(String token) {
        try {
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(this.secret)
                    .parseClaimsJws(token)
                    .getBody();

            User user = new User();
            Long id = Long.valueOf(body.get("id").toString());
            user.setId(id);

            String redisKey = "TANHUA_USER_MOBILE_" + id;
            Boolean b = redisTemplate.hasKey(redisKey);
            if (b != null && b) {
                String mobile = redisTemplate.opsForValue().get(redisKey);
                user.setMobile(mobile);
            } else {
                user = userMapper.selectPhoneById(id);
                long timeOut = Long.parseLong(body.get("exp").toString()) * 1000 - System.currentTimeMillis();
                redisTemplate.opsForValue().set(redisKey, user.getMobile(), timeOut, TimeUnit.MILLISECONDS);
            }
            return user;
        } catch (ExpiredJwtException e) {
            log.info("token已经过期！ token = " + token);
        } catch (Exception e) {
            log.error("token不合法！ token = " + token, e);
        }
        return null;
    }
}
